import { defineStore } from 'pinia';
import type { Permission, DynamicRoute, UserInfo } from '@/types/rs/Permission';
import $http from "@/types/rs/request";
import type { RouteRecordRaw } from "vue-router";
import router from "@/router";

const modules = import.meta.glob(['/src/**/**/*.vue']);

export const useAuthStore = defineStore('auth', {
    state: () => ({
        permissions: [] as Permission[],          // 菜单权限列表
        dynamicRoutes: [] as DynamicRoute[],     // 动态路由列表
        processedRoutes: {} as Record<string, boolean>, // 已处理的路由记录
        permissionsButton: [] as Permission[],   // 按钮权限列表
        userInfo: { user: null, permission: null, token: null } as UserInfo, // 用户信息
    }),
    getters: {
        // 获取用户名，默认为 '默认用户'
        getUserName: (state) => state.userInfo?.user?.userName ?? '默认用户',
    },
    actions: {
        // 初始化用户信息
        initUserInfo() {
            try {
                const userInfoStr = localStorage.getItem('userInfo');
                if (userInfoStr) {
                    this.userInfo = JSON.parse(userInfoStr);
                    console.log('已从localStorage恢复用户信息');
                }
                this.initPermissionsButton(); // 同时初始化按钮权限
            } catch (error) {
                console.error('恢复用户信息失败:', error);
                localStorage.removeItem('userInfo');
                this.userInfo = {} as UserInfo;
            }
        },

        // 初始化按钮权限
        initPermissionsButton() {
            try {
                const permissionsButtonStr = localStorage.getItem('permissionsButton');
                if (permissionsButtonStr) {
                    this.permissionsButton = JSON.parse(permissionsButtonStr);
                    console.log('已从localStorage恢复按钮权限信息', this.permissionsButton);
                }
            } catch (error) {
                console.error('恢复按钮权限信息失败:', error);
                localStorage.removeItem('permissionsButton');
                this.permissionsButton = [];
            }
        },

        // 获取按钮权限数据
        async fetchPermissionAboutButton() {
            try {
                const res = await $http.get('/erpbase/base/selectPrivilegeAboutButton');
                console.log('/erpbase/base/selectPrivilegeAboutButton', res.data);
                localStorage.setItem('permissionsButton', JSON.stringify(res.data));
                this.permissionsButton = res.data;
                console.log('按钮权限数据已更新到store', this.permissionsButton);
            } catch (err) {
                console.log('获取权限数据失败：', err);
            }
        },

        // 检查是否拥有特定权限
        hasPermission(privPerm: string): boolean {
            if (!this.permissionsButton || !Array.isArray(this.permissionsButton)) {
                console.warn('permissionsButton未定义或不是数组', this.permissionsButton);
                return false;
            }
            return this.permissionsButton.some(perm => perm.privPerm == privPerm);
        },

        // 登出
        logout() {
            this.userInfo = {} as UserInfo;
            this.permissions = [];
            this.permissionsButton = [];
            localStorage.removeItem('userInfo');
            localStorage.removeItem('permissions');
            localStorage.removeItem('permissionsButton');
            localStorage.removeItem('processedRoutes');
            localStorage.removeItem('menuPaths');
            localStorage.removeItem('menuTree');
        },

        // 初始化 token（从 localStorage 恢复）
        initializeToken() {
            this.initUserInfo();
        },

        // 获取用户权限数据并适配后端结构
        async fetchPermissions(): Promise<void> {
            try {
                const userId = this.userInfo?.user?.id || 1; // 默认 userId 为 1
                const response = await $http.get(`/permissions/user/${userId}`);
                const { code, msg, data } = response.data;

                if (code === '200') {
                    // 递归函数：将后端 Permission 转换为前端 Permission
                    const mapPermission = (item: any): Permission => ({
                        id: item.id,
                        privName: item.name, // 后端 name -> 前端 privName
                        privUrl: item.purl,  // 后端 purl -> 前端 privUrl
                        visible: item.is_delete === 0 ? 0 : 1, // is_delete 为 0 表示可见
                        icon: item.children && item.children.length > 0 ? 'Folder' : 'Document', // 根据子节点设置图标
                        parentId: item.pid || 0, // 后端 pid -> 前端 parentId
                        children: item.children ? item.children.map(mapPermission) : [] // 递归处理子节点
                    });

                    // 转换权限数据
                    const adaptedPermissions = data.map(mapPermission);
                    this.permissions = adaptedPermissions;
                    localStorage.setItem('permissions', JSON.stringify(adaptedPermissions));

                    // 清空已处理路由记录
                    this.processedRoutes = {};
                    localStorage.setItem('processedRoutes', JSON.stringify(this.processedRoutes));

                    // 清除其他缓存
                    localStorage.removeItem('menuPaths');
                    localStorage.removeItem('menuTree');
                } else {
                    throw new Error('权限接口返回错误: ' + msg);
                }
            } catch (error) {
                console.error('获取权限失败:', error);
                throw error;
            }
        },

        // 解析组件路径
        resolveComponent(path: string | null | undefined) {
            if (!path) return undefined;
            const importPage = modules[`/src/${path}.vue`];
            if (!importPage) {
                console.warn(`组件不存在: /src/${path}.vue`);
                return undefined;
            }
            return importPage;
        },

        // 生成动态路由
        generateRoutes(): DynamicRoute[] {
            const routes: DynamicRoute[] = [
                {
                    path: '/login',
                    name: 'Login',
                    meta: { title: '登录' },
                    component: () => import('@/public-view/Login.vue')
                }
            ];

            const generateRouteFromPermission = (perm: Permission, parentPerm?: Permission): DynamicRoute | null => {
                if (perm.visible !== 0) return null;

                const pathSegment = perm.privUrl || `dir_${perm.id}`;
                const isTopLevel = perm.parentId === 0 && perm.privUrl !== '/';
                const finalPath = isTopLevel ? `${pathSegment}` : pathSegment;

                const route: DynamicRoute = {
                    path: finalPath,
                    name: perm.privName,
                    meta: {
                        title: perm.privName,
                        icon: perm.icon || undefined,
                        parent: parentPerm ? parentPerm.privName : undefined
                    },
                    children: []
                };

                // 处理组件加载
                if (perm.component && perm.component.trim()) {
                    const componentPath = perm.component.trim().replace(/^\//, '');
                    const componentLoader = this.resolveComponent(componentPath);
                    if (componentLoader) {
                        route.component = componentLoader;
                    } else {
                        console.warn(`无法加载组件: ${componentPath}`);
                    }
                }

                // 处理子路由
                if (perm.children && perm.children.length) {
                    route.children = perm.children
                        .filter(child => child.visible === 0)
                        .map(child => generateRouteFromPermission(child, perm))
                        .filter((child): child is DynamicRoute => child !== null);
                }

                return route;
            };

            const topLevelRoutes = this.permissions
                .filter(perm => perm.visible === 0 && perm.parentId === 0)
                .map(perm => generateRouteFromPermission(perm))
                .filter((route): route is DynamicRoute => route !== null);

            routes.push(...topLevelRoutes);
            this.dynamicRoutes = routes;
            return routes;
        },

        // 动态添加路由
        addRoutes() {
            const routerLoop = (routes: DynamicRoute[], parentPath: string = '', parentName?: string) => {
                routes.forEach((item) => {
                    const fullPath = parentPath 
                        ? (item.path.startsWith('/') 
                            ? item.path 
                            : `${parentPath}/${item.path.replace(/^\//, '')}`)
                        : item.path;

                    const routeKey = fullPath;
                    if (this.processedRoutes[routeKey]) {
                        console.log(`路由已存在，跳过添加: ${routeKey}`);
                        return;
                    }

                    const route: RouteRecordRaw = {
                        path: item.path,
                        name: item.name,
                        component: item.component,
                        meta: item.meta,
                        children: [],
                    };

                    if (parentName) {
                        router.addRoute(parentName, route);
                    } else {
                        router.addRoute(route);
                    }

                    this.processedRoutes[routeKey] = true;
                    localStorage.setItem('processedRoutes', JSON.stringify(this.processedRoutes));

                    if (item.children && item.children.length > 0) {
                        routerLoop(item.children, fullPath, item.name);
                    }
                });
            };

            routerLoop(this.dynamicRoutes);
            console.log('已处理的路由:', this.processedRoutes);
            console.log('当前路由列表:', router.getRoutes());
        },
    }
});